package middleware

import (
	"net/http"
	"strings"
)

type FilterHandle func(w http.ResponseWriter, r *http.Request) error

type Filter struct {
	filterMap map[string]FilterHandle
}

func NewFilter() *Filter {
	return &Filter{filterMap: make(map[string]FilterHandle)}
}

//注册拦截器
func (f *Filter) RegisterFilterUri(uri string, handler FilterHandle) {
	f.filterMap[uri] = handler
}

//根据uri获取handle
func (f *Filter) GetFilterUri(uri string) FilterHandle {
	return f.filterMap[uri]
}

type WebHandle func(w http.ResponseWriter, r *http.Request)

//执行拦截器
func (f *Filter) Handle (webHandle WebHandle) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		for path, handle := range f.filterMap {
			//拦截业务逻辑
			if strings.Contains(r.RequestURI, path){
				err := handle(w,r)
				if err != nil {
					w.Write([]byte(err.Error()))
					return
				}
				break
			}
		}
		webHandle(w,r)
	}
}
